<?php

namespace App\Jobs;

use App\Lib\Uploads\UploadHandler;
use App\Models\WxAttachment;
use App\Wen\Utils\FileUtils;
use App\Wen\Utils\Settings;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Carbon;

class ImageUnusedCleanJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        global $__MINI_GLOBAL_PAYCODE_3__;
        if(!$__MINI_GLOBAL_PAYCODE_3__){
            return;
        }

        $after_days = Settings::get('image_unused_keep_days', 10);
        $attachments = WxAttachment::where([ [ 'state', '=', 0 ], [ 'created_at', '<', Carbon::now()->subDays($after_days) ] ])->get();
        if($attachments){

            foreach ($attachments as $the_attachment){
                if($the_attachment){
                    if(UploadHandler::del($the_attachment)){

                    }else{
                        _logger_(__file__, __line__, '清理附件失败');
                    }
                }else{
                    _logger_(__file__, __line__, '不存在附件表的url地址');
                }
            }
        }
        __system__del__dir(storage_path('tmp/images'));
    }
}
